package com.davesandoval.tpdroid;

import harmony.java.awt.Color;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import com.lowagie.text.pdf.draw.VerticalPositionMark;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewPrintableSO extends Activity {
	public static final int SIGNATURE_ACTIVITY = 1;

	private String soNum;
	private String[] printableSO;
	private String sigName;
	private String sigPath;
	private ImageView ivSignature;
	private static String signatureURI;
	private static File signature;
	private String yourName;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewprintableso);
		Bundle extras = getIntent().getExtras();
		soNum = extras.getString("soNum");

		Button btnCaptureSignature = (Button) findViewById(R.id.btnGetSignature);
		Button btnSaveToPDF = (Button) findViewById(R.id.btnSaveToPDF);
		ivSignature = (ImageView) findViewById(R.id.ivSignature);
		TextView tvPrintableSO = (TextView) findViewById(R.id.tvPrintableSO);
		tvPrintableSO.setMovementMethod(new ScrollingMovementMethod());
		signatureURI = "sig" + soNum + ".png";
		signature = new File("sig" + soNum + ".png");

		try {
			printableSO = Main.client.getPrintableSO(soNum);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String output = "";
		for (int i = 0; i < printableSO.length; i++) {
			output = output + printableSO[i] + "\n";
		}

		tvPrintableSO.setText(output);
		System.out.println(output);

		btnCaptureSignature.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ViewPrintableSO.this,
						CaptureSignature.class);
				intent.putExtra("soNum", soNum);
				startActivityForResult(intent, SIGNATURE_ACTIVITY);
			}
		});
		
		btnSaveToPDF.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				printToPDF(soNum);
				Uri file = Uri.parse("/sdcard/TPDroid/ServiceOrder" + soNum + ".pdf");
				Intent pdfView = new Intent(Intent.ACTION_SEND);
				pdfView.setType("application/pdf");
                pdfView.putExtra(Intent.EXTRA_STREAM, file);
					startActivity(Intent.createChooser(pdfView, "Send PDF using"));
			}
		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case SIGNATURE_ACTIVITY:
			if (resultCode == RESULT_OK) {

				Bundle bundle = data.getExtras();
				String status = bundle.getString("status");
				yourName = bundle.getString("typedName");
				sigName = bundle.getString("sigName");
				sigPath = bundle.getString("sigPath");
				System.out.println("--image file--\\--" + sigPath + sigName);
				signature = new File(sigPath + sigName);
				if (status.equalsIgnoreCase("done")) {
					Toast toast = Toast
							.makeText(this, "Signature capture successful!",
									Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP, 105, 50);
					toast.show();
				}
			}
			break;
		}
	}

	protected void onResume() {
		System.out.println("------ViewPrintableSOActivity onResume------");
		Bitmap bm = BitmapFactory.decodeFile(sigPath + sigName);
		ivSignature.setImageBitmap(bm);
		super.onResume();
	}

	protected void printToPDF(String soNum) {
		Font defaultFont = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL,
				new Color(0, 0, 0));
		Font boldFont = new Font(Font.TIMES_ROMAN, 8, Font.BOLD, new Color(0,
				0, 0));
		Font titleFont = new Font(Font.TIMES_ROMAN, 10, Font.BOLD, new Color(0,
				0, 0));
		DateFormat today = DateFormat.getDateInstance(DateFormat.MEDIUM);
		Date myDate = new Date();
		Toast toast = Toast.makeText(this,
				"One second please, creating PDF...", Toast.LENGTH_LONG);
		toast.show();

		try {
			Document document = new Document(PageSize.A4);
			PdfWriter pdfWriter = PdfWriter.getInstance(document,
					new FileOutputStream("/mnt/sdcard/TPDroid/ServiceOrder"
							+ soNum + ".pdf"));
			document.open();
			document.addAuthor("NuWave Technology Partners");
			document.addCreator("TPDroid");
			document.addSubject("SO Number: " + soNum);
			document.addCreationDate();
			document.addTitle("SO Number: " + soNum);

			String[] output = Main.client.getPrintableSO(soNum);
			Chunk tab = new Chunk(new VerticalPositionMark(), 450, true); // far right 450
			Chunk tab2 = new Chunk(new VerticalPositionMark(), 370, true); // not as far right 370
			Chunk tab3 = new Chunk(new VerticalPositionMark(), 200, true); // just about in the center 200
			Chunk tab4 = new Chunk(new VerticalPositionMark(), 100, true); // 100
			Chunk tab5 = new Chunk(new VerticalPositionMark(), 400, true); // 400
			Chunk tab6 = new Chunk(new VerticalPositionMark(), 315, true); // 315

			Chunk line = new Chunk(new LineSeparator(0.5f, 40, null,
					Element.ALIGN_CENTER, 3.5f));
			Chunk leftLine = new Chunk(new LineSeparator(0.5f, 40, null,
					Element.ALIGN_LEFT, 3.5f));

			Paragraph p = new Paragraph();
			p.add(new Chunk(output[0], titleFont)); // Company Name
			p.add(Chunk.NEWLINE);
			p.add(new Chunk(output[1], defaultFont)); // Company Address
			p.add(tab);
			p.add(new Chunk(output[5], titleFont)); // Service Order title
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[2], defaultFont)); // Company address
			p.add(tab);
			p.add(new Chunk(output[6], defaultFont)); // Service Order number
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[3], defaultFont)); // Phone/Fax
			p.add(tab);
			p.add(new Chunk(output[7], defaultFont)); // Date
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[4], defaultFont)); // Email address
			p.add(Chunk.NEWLINE);
			p.add(line);
			p.add(Chunk.NEWLINE);
			p.add(tab3);
			p.add(new Chunk("Ship-To", defaultFont));
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[8], defaultFont)); // Account info
			p.add(tab2);
			p.add(new Chunk(output[13], defaultFont));
			p.add(tab);
			p.add(new Chunk(output[14], defaultFont));
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[9], boldFont)); // Account Name
			p.add(tab2);
			p.add(new Chunk(output[15], defaultFont));
			p.add(tab);
			p.add(new Chunk(output[16], defaultFont));
			p.add(new Chunk("      ", defaultFont));
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[10], boldFont)); // Account Address
			p.add(tab2);
			p.add(new Chunk(output[17], defaultFont));
			p.add(tab);
			p.add(new Chunk(output[18], defaultFont));
			p.add(Chunk.NEWLINE);

			p.add(new Chunk(output[11], boldFont)); // Account Address
			p.add(tab2);
			p.add(new Chunk(output[19], defaultFont));
			p.add(tab);
			p.add(new Chunk(output[20], defaultFont));
			p.add(Chunk.NEWLINE);
			p.add(new Chunk(output[12], defaultFont));// Contact
			p.add(Chunk.NEWLINE);
			p.add(line);
			p.add(Chunk.NEWLINE);

			p.add(new Chunk("Description: ", boldFont)); // Description
			p.add(new Chunk(output[21], defaultFont)); // Description
			p.add(tab6);
			p.add(new Chunk("Priority: ", boldFont));
			p.add(new Chunk(output[22], defaultFont)); // Priority
			p.add(tab);
			p.add(new Chunk("Status: ", boldFont));
			p.add(new Chunk(output[23], defaultFont)); // Status
			p.add(Chunk.NEWLINE);

			p.add(new Chunk("Taken By: ", boldFont));
			p.add(new Chunk(output[24], defaultFont)); // TakenBy
			p.add(tab4);
			p.add(new Chunk("System: ", boldFont));
			p.add(new Chunk(output[25], defaultFont)); // System
			p.add(tab3);
			p.add(new Chunk("Type: ", boldFont));
			p.add(new Chunk(output[26], defaultFont)); // SO Type
			p.add(tab6);
			p.add(new Chunk("Payment: ", boldFont));
			p.add(new Chunk(output[27], defaultFont)); // Payment
			p.add(tab5);
			p.add(new Chunk("Assigned To: ", boldFont));
			p.add(new Chunk(output[28], defaultFont)); // Assigned to
			p.add(new Chunk("Directions: ", boldFont));
			p.add(new Chunk(output[29], defaultFont)); // Directions
			p.add(Chunk.NEWLINE);
			p.add(new Chunk("Problem: ", boldFont));
			p.add(new Chunk(output[30], defaultFont)); // Problem
			p.add(Chunk.NEWLINE);
			p.add(new Chunk("Work Performed: ", boldFont));
			p.add(Chunk.NEWLINE);

			int loop = 31;
			while (output[loop].toString().compareTo("Time Logs:") != 0) {
				p.add(new Chunk(output[loop], defaultFont)); // Work Performed
				p.add(new Chunk("  ", defaultFont));
				loop++;
			}
			p.add(Chunk.NEWLINE);
			p.add(new Chunk("Time Logs: ", boldFont));
			p.add(Chunk.NEWLINE);

			for (int i = loop + 1; i < output.length; i++) {
				p.add(new Chunk(output[i], defaultFont)); //Time logs
				p.add(Chunk.NEWLINE);
			}

			p.add(leftLine);
			p.add(Chunk.NEWLINE);

			p.add(new Chunk("Date: ___/___/___     Travel Time: _________",
					defaultFont));
			p.add(Chunk.NEWLINE);
			p.add(new Chunk("Arrived At: _________     Departed At: _________",
					defaultFont));
			p.add(Chunk.NEWLINE);
			p.add(Chunk.NEWLINE);
			document.add(p);

			Paragraph o = new Paragraph();
			o.add(new Chunk("CUSTOMER SIGNATURE:", defaultFont));
			if (signature.exists()) {
				Image sig = Image.getInstance(sigPath + sigName);
				sig.scalePercent(50);
				o.add(sig);
				o.add(new Chunk(yourName));
			} else {
				//o.add(new Chunk("There is no signature", titleFont));
				o.add(Chunk.NEWLINE);
				o.add(Chunk.NEWLINE);
				o.add(Chunk.NEWLINE);
				o.add(Chunk.NEWLINE);
				o.add(leftLine);
			}
			o.add(Chunk.NEWLINE);
			o.add(leftLine);
			o.add(Chunk.NEWLINE);
			o.add(Chunk.NEWLINE);
			o.add(new Chunk("Tech Signature:", defaultFont));
			o.add(Chunk.NEWLINE);
			o.add(Chunk.NEWLINE);
			o.add(Chunk.NEWLINE);
			o.add(leftLine);
			o.add(Chunk.NEWLINE);
			o.add(new Chunk("Printed: " + today.format(myDate), defaultFont));

			document.add(o);

			document.close();
			Toast t = Toast.makeText(this, "PDF ServiceOrder" + soNum
					+ ".pdf successfully created!\n\n"
					+ "It will be in your TPDroid folder on your SDCard.",
					Toast.LENGTH_LONG);
			t.show();

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
